<!DOCTYPE html>
<html>
<head>
    <title>MBTI测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <style>
        .test-header {
            background: rgba(255, 255, 255, 0.9);
            padding: 15px 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .test-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .test-length-badge {
            font-size: 0.9rem;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .length-20 {
            background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
            color: white;
        }
        
        .length-60 {
            background: linear-gradient(135deg, #FFC107 0%, #FF9800 100%);
            color: white;
        }
        
        .length-120 {
            background: linear-gradient(135deg, #F44336 0%, #E91E63 100%);
            color: white;
        }
        
        /* 其他样式保持不变... */
    </style>
</head>
<body class="gradient-bg">
    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <div class="container mt-3">
                <div class="alert alert-info alert-dismissible fade show" role="alert">
                    {% for message in messages %}
                        <div>{{ message }}</div>
                    {% endfor %}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            </div>
        {% endif %}
    {% endwith %}
    
    <div class="container py-5">
        <div class="test-header">
            <div class="test-info">
                <div>
                    <h3 class="mb-0">MBTI性格测试</h3>
                    <div class="text-muted">根据您的选择进行测试</div>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <span class="test-length-badge length-{{ session.get('test_length', 20) }}">
                        {{ session.get('test_length', 20) }}题测试
                    </span>
                    <a href="/select_test_length" class="btn btn-sm btn-outline-secondary">
                        <i class="bi bi-arrow-repeat me-1"></i>重新选择
                    </a>
                </div>
            </div>
        </div>
        
        <!-- 固定在顶部的进度条 -->
        <div class="sticky-progress">
            <div class="progress-container">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div>
                        <span class="fw-bold">测试进度</span>
                        <span id="progress-percent" class="ms-2 fw-bold text-primary">{{ progress|int }}%</span>
                    </div>
                    <div class="text-muted small">
                        <span id="answered-count">0</span> / {{ questions|length }} 题已回答
                    </div>
                </div>
                <div class="progress">
                    <div id="test-progress" 
                         class="progress-bar bg-info progress-bar-striped progress-bar-animated" 
                         role="progressbar" 
                         style="width: {{ progress }}%" 
                         aria-valuenow="{{ progress }}" 
                         aria-valuemin="0" 
                         aria-valuemax="100"></div>
                </div>
            </div>
        </div>
        
        <!-- 保存提示 -->
        <div class="save-indicator" id="save-indicator">
            <i class="bi bi-check-circle me-1"></i>进度已保存
        </div>
        
        <div class="card shadow-lg animate-card">
            <div class="card-body">
                <form method="POST" id="test-form">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    
                    {% for q in questions %}
                    <div class="question-card" id="question-{{ loop.index0 }}">
                        <p class="fw-bold fs-5 text-dark mb-3">
                            <span class="badge bg-primary me-2">{{ loop.index }}</span>
                            {{ q.text }}
                        </p>
                        <div class="option-container">
                            <div class="option-item">
                                <input type="radio" 
                                       name="question_{{ loop.index0 }}" 
                                       id="q{{ loop.index0 }}a" 
                                       value="A" 
                                       required
                                       data-question="{{ loop.index0 }}"
                                       class="question-radio">
                                <label class="option-label" for="q{{ loop.index0 }}a">
                                    <span class="option-text">{{ q.options[0] }}</span>
                                </label>
                            </div>
                            <div class="option-item">
                                <input type="radio" 
                                       name="question_{{ loop.index0 }}" 
                                       id="q{{ loop.index0 }}b" 
                                       value="B" 
                                       required
                                       data-question="{{ loop.index0 }}"
                                       class="question-radio">
                                <label class="option-label" for="q{{ loop.index0 }}b">
                                    <span class="option-text">{{ q.options[1] }}</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                    
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-primary btn-hover btn-lg">
                            <i class="bi bi-send me-2"></i>提交测试
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
   <script>
    document.addEventListener('DOMContentLoaded', function() {
        const totalQuestions = {{ questions|length }};
        const progressBar = document.getElementById('test-progress');
        const progressPercent = document.getElementById('progress-percent');
        const answeredCountEl = document.getElementById('answered-count');
        const saveIndicator = document.getElementById('save-indicator');
        const stickyProgress = document.querySelector('.sticky-progress');
        
        let lastScrollPos = window.scrollY;
        let hideTimeout = null;
        
        // 滚动时隐藏/显示进度条
        window.addEventListener('scroll', function() {
            const currentScrollPos = window.scrollY;
            
            // 清除之前的超时
            if (hideTimeout) clearTimeout(hideTimeout);
            
            // 显示进度条
            stickyProgress.classList.remove('hidden');
            
            // 向下滚动时隐藏，向上滚动时显示
            if (currentScrollPos > lastScrollPos && currentScrollPos > 100) {
                // 设置延迟隐藏
                hideTimeout = setTimeout(() => {
                    stickyProgress.classList.add('hidden');
                }, 2000);
            } else {
                stickyProgress.classList.remove('hidden');
            }
            
            lastScrollPos = currentScrollPos;
        });
        
        // 从sessionStorage恢复答案
        function restoreAnswers() {
            let answered = 0;
            for (let i = 0; i < totalQuestions; i++) {
                const answer = sessionStorage.getItem(`question_${i}`);
                if (answer) {
                    const radio = document.querySelector(`input[name="question_${i}"][value="${answer}"]`);
                    if (radio) {
                        radio.checked = true;
                        answered++;
                    }
                }
            }
            return answered; // 只返回计数
        }
        
        // 更新进度
        function updateProgress(answered) {
            // 使用实际测试长度计算进度百分比
            const progress = Math.round((answered / totalQuestions) * 100);
            progressBar.style.width = `${progress}%`;
            progressBar.setAttribute('aria-valuenow', progress);
            progressPercent.textContent = `${progress}%`;
            answeredCountEl.textContent = `${answered}/${totalQuestions}`;
            
            // 更新进度条颜色
            if (progress < 30) {
                progressBar.className = 'progress-bar bg-danger progress-bar-striped progress-bar-animated';
            } else if (progress < 70) {
                progressBar.className = 'progress-bar bg-warning progress-bar-striped progress-bar-animated';
            } else {
                progressBar.className = 'progress-bar bg-success progress-bar-striped progress-bar-animated';
            }
            
            return progress; // 返回进度值
        }
        
        // 保存进度到服务器
        function saveProgressToServer(progress) {
            fetch('/save_progress', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('input[name="csrf_token"]').value
                },
                body: JSON.stringify({ progress: progress })
            })
            .then(response => {
                if (response.ok) {
                    // 显示保存提示
                    saveIndicator.classList.add('show');
                    setTimeout(() => {
                        saveIndicator.classList.remove('show');
                    }, 2000);
                }
            });
        }
        
        // 初始化恢复答案
        let answered = restoreAnswers();
        let progress = updateProgress(answered); // 更新UI并获取进度值
        saveProgressToServer(progress); // 保存初始进度
        
        // 监听选项变化
        document.querySelectorAll('.question-radio').forEach(radio => {
            radio.addEventListener('change', function() {
                const questionId = this.dataset.question;
                sessionStorage.setItem(`question_${questionId}`, this.value);
                
                // 重新计算已回答问题数
                answered = document.querySelectorAll('.question-radio:checked').length;
                progress = updateProgress(answered); // 更新进度并获取新值
                
                // 自动保存进度
                saveProgressToServer(progress);
                
                // 移动端自动滚动到下一题
                if (window.innerWidth <= 768) {
                    const nextId = parseInt(questionId) + 1;
                    const nextQuestion = document.getElementById(`question-${nextId}`);
                    
                    if (nextQuestion) {
                        // 计算滚动位置（考虑进度条高度）
                        const progressBarHeight = document.querySelector('.sticky-progress').offsetHeight;
                        const elementTop = nextQuestion.getBoundingClientRect().top;
                        const elementHeight = nextQuestion.offsetHeight;
                        const offsetPosition = elementTop + window.pageYOffset - (window.innerHeight / 2) + (elementHeight / 2) - progressBarHeight;
                        
                        // 平滑滚动
                        window.scrollTo({
                            top: offsetPosition,
                            behavior: 'smooth'
                        });
                    }
                }
            });
        });
        
        // 表单提交时清除存储
        document.getElementById('test-form').addEventListener('submit', function() {
            for (let i = 0; i < totalQuestions; i++) {
                sessionStorage.removeItem(`question_${i}`);
            }
            sessionStorage.removeItem('progress');
        });
        
        // 点击进度条时滚动到顶部
        stickyProgress.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
        
        // 防止iOS缩放
        document.addEventListener('touchmove', function(event) {
            if (event.scale !== 1) {
                event.preventDefault();
            }
        }, { passive: false });
        
        // 阻止双击缩放
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function(event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
    });
</script>
</body>
</html>